package com.phospherus.common.controller;


import com.phospherus.common.controller.handler.Data;
import com.phospherus.common.controller.handler.PageData;
import com.phospherus.common.controller.handler.ResultHandler;
import com.phospherus.common.service.IBaseService;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author songjinlong
 * @version 1.0
 * @since 2017/04/18
 */
public abstract class BaseController<T, SERVICE extends IBaseService>{
    @Autowired
    protected SERVICE service;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    protected boolean onBeforeQuery(Map<String, String> param, HttpServletRequest request) {
        return false;
    }

    @RequestMapping("/query")
    @ResponseBody
    public ResultHandler<T> query(@RequestParam Map<String, String> param, HttpServletRequest request) {
        if (onBeforeQuery(param, request)) {
            logger.debug("param error:"+param.toString());
            return new ResultHandler<>(ResultHandler.SystemMessage.SYSTEM_ERROR);
        }
        ResultHandler<T> resultHandler;
        if (param == null || (param.size() == 1 && param.containsKey("_"))) {
            List<T> list = service.findAll();
            resultHandler = new ResultHandler<>(ResultHandler.SystemMessage.SUCCESS, new Data<>(list));
        } else {
            String cp = param.get("currPage");
            String ps = param.get("pageSize");
            if (cp == null && ps == null) {
                List<T> list = service.findAll(param);
                resultHandler = new ResultHandler<>(ResultHandler.SystemMessage.SUCCESS, new Data<>(list));
            } else {
                int currPage = NumberUtils.toInt(cp, 0);
                int pageSize = NumberUtils.toInt(ps, 20);
                param.remove("currPage");
                param.remove("pageSize");
                Page<T> page = service.findAll(param, currPage, pageSize);
                resultHandler = new ResultHandler<>(ResultHandler.SystemMessage.SUCCESS, new PageData<>(page));
            }
        }
        return resultHandler;
    }
    
}